#!/usr/bin/env python

import os
import git
import threading
import cherrypy
import pymongo
import time

from settings import REPOS_PATH
from app.utils import c_date


class GitProgress(git.remote.RemoteProgress):
  def setKey(self, _id):
    self._id = _id
  
  def update(self, op_code, cur_count, max_count=None, message=''):
    db = pymongo.Connection().giuseppe
    db.clone_status.save({
      "_id": self._id,
      "op_code": op_code,
      "cur_count": cur_count,
      "max_count": max_count
    })


class GitTools:
  @staticmethod
  def _clone(name, src, dst, key):
    progress = GitProgress()
    progress.setKey(key)
    repo = git.Repo().clone_from(src, dst, progress=progress)
    
    OP_DONE = 128
    timestamp = int(time.time())
    db = pymongo.Connection().giuseppe
    
    db.projects.save({
      "name": name,
      "url": src,
      "updated": timestamp,
      "selected": False})
      
    db.clone_status.update(
      {"_id": key},
      {"$set": {"op_code": OP_DONE}})
    
  @staticmethod
  def clone_repo(name, url, key):
    path_dst = REPOS_PATH + "/" + name
    if os.path.exists(path_dst):
      return "EXIST"
    else:
      os.mkdir(path_dst)
    
    clone_thread = threading.Thread(target = GitTools._clone, 
                                    args   = (name, url, path_dst, key))
    clone_thread.start()
    return "OK"
    
  @staticmethod
  def load_repo(name):
    path = REPOS_PATH + "/" + name
    if not os.path.exists(path):
      return None
      
    return git.Repo(path)
    
  @staticmethod
  def timerange(repo, scope):
    day = 24 * 60 * 60
    today = time.time()
    since, until = today, today

    # Last 30 days
    if scope == "30days":
      since = today - 30 * day
    # Last 7 days
    elif scope == "7days":
      since = today - 7 * day
    # Last 100 commits
    elif scope == "100commits":
      c = repo.iter_commits(max_count=100, reverse=True).next()
      if c:
        since = c.committed_date - 1
    
    return int(since), int(until)
  